package com.evil.common.file.util;

import com.evil.common.core.enums.RCodeEnum;
import com.evil.common.core.exception.BusinessException;
import com.evil.common.core.util.ServletUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.function.Consumer;

/**
 * 导出工具类
 *
 * @author 15587
 * @date 2022-08-08 00:00
 */
public class ExportUtil {

    /**
     * 导出
     *
     * @param export       输出操作
     * @param versionsType versionsType
     * @param filename     filename
     */
    public static void export(Consumer<OutputStream> export, String versionsType, String filename) {
        try {
            // 将工作簿写入
            HttpServletResponse response = ServletUtils.getResponse();
            // 告诉浏览器用什么软件可以打开此文件
            response.setContentType(versionsType);
            // 下载文件的默认名称
            response.setHeader(PoiUtil.DOWN_FILE_HEADER_NAME, URLEncoder.encode(filename, "UTF-8"));
            OutputStream os = response.getOutputStream();
            export.accept(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            throw new BusinessException(RCodeEnum.ERROR_RUNTIME);
        }
    }

    /**
     * 导出
     *
     * @param export   输出操作
     * @param response response
     * @param filename filename
     */
    public static void export(Consumer<OutputStream> export, HttpServletResponse response, String filename) {
        try {
            // 下载文件的默认名称
            response.setHeader(PoiUtil.DOWN_FILE_HEADER_NAME, URLEncoder.encode(filename, "UTF-8"));
            response.setHeader(PoiUtil.CONTENT_DISPOSITION_HEADER_NAME, "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
            OutputStream os = response.getOutputStream();
            export.accept(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            throw new BusinessException(RCodeEnum.ERROR_RUNTIME);
        }
    }
}
